package com.ziq.zcamp.mine

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.GsonUtils
import com.facebook.imagepipeline.request.ImageRequest
import com.google.android.material.appbar.AppBarLayout
import com.ziq.base.base.BaseFragment
import com.ziq.base.extension.*
import com.ziq.zcamp.R
import com.ziq.zcamp.api.respond.user.UserNumRelationRespond
import com.ziq.zcamp.bean.post.ImageInfo
import com.ziq.zcamp.databinding.FragmentMineBinding
import com.ziq.zcamp.databinding.ItemMerchantFunctionBinding
import com.ziq.zcamp.login.ActionAfterLogin
import com.ziq.zcamp.login.LoginActivity
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.UserManager
import com.ziq.zcamp.util.ImageUtil
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class MineFragment : BaseFragment(R.layout.fragment_mine){

    private val binding : FragmentMineBinding? by binding()
    val userMerchantActionAdapter = MerchantActionAdapter()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding?.root
        initUserModelUI()
        UserManager.instance.userInfo.observe(viewLifecycleOwner, Observer {
            updateUserModelUI()
        })
        
    }

    override fun onResume() {
        super.onResume()
        updateUserModelUI()
    }

    //用户模式
    private fun initUserModelUI(){

        binding?.userInfoEdit?.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                    GlobalContextManager.startActivityByClass(requireContext(), UserInfoEditActivity::class.java)
                }
            })
        }
        binding?.setting?.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                    GlobalContextManager.startActivityByClass(requireContext(), SettingPageActivity::class.java)
                }
            })
        }

        binding?.llMenuUserInfo?.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                }
            })
        }

        binding?.llUserInfo?.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                }
            })
        }
        binding?.personalPage?.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                    PersonalHomePageActivity.open(requireContext(), UserManager.instance.getUid())
                }
            })
        }
        //动态点击
        binding?.llPersonalPage?.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                    PersonalHomePageActivity.open(requireContext(), UserManager.instance.getUid())
                }
            })
        }
        //关注点击
        binding?.llFollowing?.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                    MyFollowingActivity.open(requireContext(), UserManager.instance.getUid())
                }
            })
        }
        binding?.llFans?.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                    MyFansActivity.open(requireContext(), UserManager.instance.getUid())
                }
            })
        }
        binding?.llCollect?.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                    MyCollectActivity.open(requireContext(), UserManager.instance.getUid())
                }
            })
        }

        //我的服务-营地上传
        binding?.llCampUpload?.click {
            CampUploadPageActivity.open(requireContext())
        }

        binding?.llCampCoupon?.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                    MyCouponListTabActivity.open(requireContext())
                }
            })
        }

        //我的订单- 全部
        binding?.btnOrderAll?.click {
            LoginActivity.checkLogin (object : ActionAfterLogin {
                override fun action() {
                    MyOrderActivity.open(requireContext(), MyOrderActivity.TARGET_TAB_ALL)
                }
            })
        }

        binding?.btnOrderUnpaid?.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                    MyOrderActivity.open(requireContext(), MyOrderActivity.TARGET_TAB_UNPAID)
                }
            })
        }

        binding?.btnOrderWaitAccept?.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                    MyOrderActivity.open(requireContext(), MyOrderActivity.TARGET_TAB_WAIT_ACCEPT)
                }
            })
        }

        binding?.btnOrderUnused?.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                    MyOrderActivity.open(requireContext(), MyOrderActivity.TARGET_TAB_UNUSED)
                }
            })
        }

        binding?.btnOrderRefund?.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                    MyOrderActivity.open(requireContext(), MyOrderActivity.TARGET_TAB_REFUND)
                }
            })
        }

        binding?.btnOrderAppraise?.click {
            LoginActivity.checkLogin ( object : ActionAfterLogin {
                override fun action() {
                    AppraiseCenterActivity.open(requireContext())
                }
            })
        }

        binding?.rvMerchantFunction?.layoutManager = GridLayoutManager(requireContext(), 5)
        binding?.rvMerchantFunction?.adapter = userMerchantActionAdapter

        var targetHeight = GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_88)
        binding?.appBarLayout?.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
            var remain = appBarLayout.totalScrollRange - (-verticalOffset)
            if(remain <= appBarLayout.totalScrollRange / 3){
                binding?.llMenuUserInfo?.alpha = 1.0f
                binding?.llMenuUserInfo?.isClickable = true
                binding?.menuAvator?.isClickable = true
            }else {
                binding?.llMenuUserInfo?.alpha = 0f
                binding?.llMenuUserInfo?.isClickable = false
                binding?.menuAvator?.isClickable = false
            }

            if((binding?.topBg?.height?:0) > 100){
                val translationY = (-verticalOffset).toFloat() / appBarLayout.totalScrollRange.toFloat() * ((binding?.topBg?.height?:0) - targetHeight)
                binding?.menuBg?.translationY = -translationY
            } else {
                binding?.menuBg?.translationY = verticalOffset.toFloat()
            }

        })

        binding?.clUserModel?.visibility = View.VISIBLE
    }


    private fun updateUserModelUI(){
        val userInfo = UserManager.instance.userInfo.value
        if(userInfo != null){
            binding?.menuName?.text = userInfo.nick_name
            binding?.name?.text = userInfo.nick_name
            binding?.userId?.visibility = View.VISIBLE
            binding?.userId?.text = "ID: ${userInfo.uid}"
            if(userInfo.description?.isNotEmpty() == true){
                binding?.introduce?.visibility = View.VISIBLE
                binding?.introduce?.text = "${userInfo.description}"
                val lp = binding?.topBg?.layoutParams as ViewGroup.LayoutParams?
                lp?.height = GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_267)
                binding?.topBg?.layoutParams = lp

            } else {
                binding?.introduce?.visibility = View.GONE
                val lp = binding?.topBg?.layoutParams as ViewGroup.LayoutParams?
                lp?.height = GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_231)
                binding?.topBg?.layoutParams = lp
            }
            binding?.imagePersonalBgMask?.visibility = View.VISIBLE

            val imageList: List<ImageInfo> = GsonUtils.fromJson(userInfo.header_img, GsonUtils.getListType(ImageInfo::class.java))
            var headerInfo = imageList.getOrNull(0)

            ImageUtil.updateImageFromNetwork(binding?.menuAvator, headerInfo?.url, ImageRequest.CacheChoice.DEFAULT)
            binding?.menuAvator?.click {
                val list = ArrayList<String>()
                list.add(headerInfo?.url?:"")
                PicturePreviewActivity.open(requireActivity(), list, 0)
            }
            ImageUtil.updateImageFromNetwork(binding?.avator, headerInfo?.url, ImageRequest.CacheChoice.DEFAULT)
            binding?.avator?.click {
                val list = ArrayList<String>()
                list.add(headerInfo?.url?:"")
                PicturePreviewActivity.open(requireActivity(), list, 0)
            }
            ImageUtil.updateImageFromNetwork(binding?.topBg, userInfo.bg_url?:"", ImageRequest.CacheChoice.DEFAULT)

            requestUserNumRelations()
            updateUserOrderCount()
        } else {
            binding?.menuName?.text = "点击登录/注册"
            binding?.name?.text = "点击登录/注册"
            binding?.userId?.visibility = View.GONE
            binding?.userId?.text =""
            binding?.introduce?.visibility = View.GONE
            val lp = binding?.topBg?.layoutParams as ViewGroup.LayoutParams?
            lp?.height = GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_231)
            binding?.topBg?.layoutParams = lp
            ImageUtil.updateImageFromNetwork(binding?.topBg, "", ImageRequest.CacheChoice.DEFAULT)
            binding?.imagePersonalBgMask?.visibility = View.GONE
            ImageUtil.updateImageFromNetwork(binding?.menuAvator, "", ImageRequest.CacheChoice.DEFAULT)
            binding?.menuAvator?.click {}
            ImageUtil.updateImageFromNetwork(binding?.avator, "", ImageRequest.CacheChoice.DEFAULT)
            binding?.avator?.click {}

            updateUserPostFansInfo(null)
            updateUserOrderCount()
        }
    }


    inner class MerchantActionAdapter : RecyclerView.Adapter<BindingViewHolder<ItemMerchantFunctionBinding>>(){

        init {
            setHasStableIds(true)
        }

        private var dataList = mutableListOf<MerchantFunctionItem>()
        fun setData(list: MutableList<MerchantFunctionItem>) {
            dataList = list
            notifyDataSetChanged()
        }

        override fun getItemCount(): Int {
            return dataList.size
        }

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): BindingViewHolder<ItemMerchantFunctionBinding> {
            return createBindingViewHolder(parent)
        }

        override fun onBindViewHolder(
            holder: BindingViewHolder<ItemMerchantFunctionBinding>,
            position: Int
        ) {
            val item = dataList[position]
            holder.binding.ivIcon.setImageResource(item.icon)
            holder.binding.tvText.text = item.text
            holder.binding.root.click {
                item.action()
            }
            updateCount(holder.binding.tvCount, item.count())
            if (!holder.binding.tvCount.isVisible){
                holder.binding.ivPoint.isVisible = item.redPoint?.invoke()?:false
            }
        }

    }

    data class  MerchantFunctionItem(@DrawableRes val icon : Int, val text : String, val count: () -> Int, val action : () -> Unit, val redPoint : (() -> Boolean) ?= null)

    fun updateCount(tv: TextView?, count:Int){
        when {
            count == 0 -> {
                tv?.visibility = View.GONE
            }
            count > 99 -> {
                tv?.visibility = View.VISIBLE
                tv?.text = "99+"
            }
            else -> {
                tv?.visibility = View.VISIBLE
                tv?.text = "$count"
            }
        }
    }




    private fun requestUserNumRelations(){
        launchWithTry (whenTry = {
            if(UserManager.instance.isLogin.value == true){
                UserManager.instance.getNumRelation(UserManager.instance.getUid(),
                    onSuccess = {
                        updateUserPostFansInfo(it)
                    }, onFail = {
                    }
                )
            }
        })
    }

    //更新用户粉丝、收藏等信息
    private fun updateUserPostFansInfo(it: UserNumRelationRespond?){
        if(it == null){
            binding?.tvPostingCount?.text = "0"
            binding?.tvPostingCountUnit?.text = ""
            binding?.tvFollowingCount?.text = "0"
            binding?.tvFollowingCountUnit?.text = ""
            binding?.tvFansCount?.text = "0"
            binding?.tvFansCountUnit?.text = ""
            binding?.tvCollectCount?.text = "0"
            binding?.tvCollectCountUnit?.text = ""
        } else {
            if(it.data?.isNotEmpty() == true){
                var post = it.data!![0].num_post
                if(post > 10000){
                    binding?.tvPostingCount?.text = String.format("%.1f", (post / 10000.0))
                    binding?.tvPostingCountUnit?.text = GlobalContextManager.getString(R.string.wan)
                } else {
                    binding?.tvPostingCount?.text = post.toString()
                    binding?.tvPostingCountUnit?.text = ""
                }

                var following = it.data!![0].num_followings
                if(following > 10000){
                    binding?.tvFollowingCount?.text = String.format("%.1f", (following / 10000.0))
                    binding?.tvFollowingCountUnit?.text = GlobalContextManager.getString(R.string.wan)
                } else {
                    binding?.tvFollowingCount?.text = following.toString()
                    binding?.tvFollowingCountUnit?.text = ""
                }

                var followers = it.data!![0].num_fans
                if(followers > 10000){
                    binding?.tvFansCount?.text = String.format("%.1f", (followers / 10000.0))
                    binding?.tvFansCountUnit?.text = GlobalContextManager.getString(R.string.wan)
                } else {
                    binding?.tvFansCount?.text = followers.toString()
                    binding?.tvFansCountUnit?.text = ""
                }

                var collect = it.data!![0].num_collect
                if(collect > 10000){
                    binding?.tvCollectCount?.text = String.format("%.1f", (collect / 10000.0))
                    binding?.tvCollectCountUnit?.text = GlobalContextManager.getString(R.string.wan)
                } else {
                    binding?.tvCollectCount?.text = collect.toString()
                    binding?.tvCollectCountUnit?.text = ""
                }

            }
        }
    }

    //用户订单 角标
    private fun updateUserOrderCount(){
        UserManager.instance.userOrderStatisticsInfo.value.let {
            updateCount(binding?.tvOrderUnpaidCount, (it?.paying_num?:0) + (it?.act_paying_num?:0))
            updateCount(binding?.tvOrderWaitAcceptCount, (it?.receiving_num?:0) + (it?.act_receiving_num?:0))
            updateCount(binding?.tvOrderUnusedCount, (it?.finishing_num?:0) + (it?.act_finishing_num?:0))
            updateCount(binding?.tvOrderAppraiseCount,(it?.to_comment_num?:0))
        }
    }
}